package com.demo01.client;

import com.demo01.core.DemoPacket;
import com.demo01.core.HelloPacket;
import com.demo01.core.RuiSingPacket;
import com.demo01.server.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.TioConfig;
import org.tio.core.exception.TioDecodeException;
import org.tio.core.intf.Packet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/31 2:24 下午
 */
public class ClientDemoHandler implements ClientAioHandler {
    private static final Logger log = LoggerFactory.getLogger(ClientDemoHandler.class);


    @Override
    public HelloPacket decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws TioDecodeException {

        byte[] packetData = new byte[readableLength];
        buffer.get(packetData, position, readableLength);
        HelloPacket helloPacket = new HelloPacket();
        helloPacket.setBody(packetData);
        return helloPacket;
    }

    @Override
    public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
        HelloPacket helloPacket = (HelloPacket) packet;
        ByteBuffer buffer = ByteBuffer.wrap(helloPacket.getBody());

        return buffer;
    }


    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        HelloPacket helloPacket = (HelloPacket) packet;
        log.info("packet , msg={}, userId={}, ip={}", helloPacket.toString(), channelContext.userid, channelContext.getClientNode().getIp());
    }

    @Override
    public HelloPacket heartbeatPacket(ChannelContext channelContext) {
        return null;
    }

}
